#include <iostream>
#include <QObject>
#include <QDebug>
#include <QSettings>
#include <QCoreApplication>
#include <QTcpServer>
#include <thread>

#include "wifi_iepe.h"
int main(int argc,char *argv[])
{
    QCoreApplication app(argc,argv);
    QSettings settings("config.ini", QSettings::IniFormat);
    settings.beginGroup("tcp");
    int port = settings.value("port", 9000).toInt();
    settings.endGroup();

    QTcpServer* server = new QTcpServer();
    if(!server->listen(QHostAddress::Any,port)){
        qDebug() << "Failed to start server:" << server->errorString();
        return 1;
    }
    QObject::connect(server, &QTcpServer::newConnection, [&]() {
        std::thread([&]{
            QTcpSocket *clientSocket = server->nextPendingConnection();
            qDebug() << "New client connected:" << clientSocket->peerAddress().toString();
            IEPE_Command* command = new IEPE_Command(clientSocket);
            try{
                while(clientSocket->isValid()) {
                    command->query();
                    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                }
            }catch(std::exception e){
                qDebug()<<e.what();
            }
            clientSocket->close();
        }).detach();
    });
    
    return app.exec();
}